import requests
import json
import schedule
from wxauto import WeChat
import os
import time
from datetime import datetime, timedelta
from openai import OpenAI

list_name = ['本人']  # 接收消息的微信好友名称

baidu_api_key = "ygfRHS0Po6rYaTfkSskOe5lf"
baidu_api_secret = "mn2h3psmGsH2bTQZz3kNYaFBRLadikAk"


def get_access_token():
    """ 获取百度AI的access_token """
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={baidu_api_key}&client_secret={baidu_api_secret}"
    response = requests.get(url)
    try:
        return response.json().get("access_token")
    except (json.JSONDecodeError, KeyError) as e:
        print(f"获取access_token失败: {e}")
        return None


def send_message(wx1, message, recipient):
    """ 发送微信消息 """
    try:
        wx1.SendMsg(msg=message, who=recipient)
        print(f"已发送消息: {message} 给 {recipient}")
    except Exception as e:
        print(f"发送消息失败: {e}")


def main(wx1, msg):
    """ 处理来自微信好友的消息 """
    if msg.startswith("AI"):  # 检查消息是否以"AI"开头
        access_token = get_access_token()
        if access_token:
            url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-lite-8k?access_token={access_token}"
            payload = json.dumps({"messages": [{"role": "user", "content": msg[2:]}]})
            headers = {'Content-Type': 'application/json'}
            response = requests.post(url, headers=headers, data=payload)
            try:
                json_result = response.json()
                wx1.SendMsg(msg=json_result['result'], who=list_name[0])  # 发送AI回复
            except (json.JSONDecodeError, KeyError) as e:
                print(f"处理百度AI回复失败: {e}")
                wx1.SendMsg(msg="抱歉，百度AI接口调用失败", who=list_name[0])  # 发送错误信息

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)


def get_qianwen_response(user_input, knowledge_base=""):
    """使用通义千问 API 获取响应"""
    try:
        prompt = (
            f"作为一个助理，你需要根据用户的请求和以下知识库提供帮助。\n"
            f"知识库内容：{knowledge_base}\n"
            f"用户询问：{user_input}\n"
        )

        completion = client.chat.completions.create(
            model="qwen-turbo",
            messages=[
                {'role': 'system', 'content': '你是一个有帮助的助手。'},
                {'role': 'user', 'content': prompt}
            ],
        )
        response_message = completion.choices[0].message.content
        return response_message
    except Exception as e:
        return f"请求出错: {str(e)}"


def send_daily_advice(wx1):
    """生成明天的穿衣出行建议发送至微信"""
    try:
        # 从文件中读取天气信息
        weather_info = read_weather_info('weather.txt')

        tomorrow = datetime.now() + timedelta(days=1)
        date_str = tomorrow.strftime('%Y年%m月%d日')

        # 使用 AI 生成穿衣出行建议
        ai_response = get_qianwen_response(
            f"根据以下天气信息和明天的日期（{date_str}），请给明天的穿衣出行建议：{weather_info}")

        # 发送 AI 的回复
        wx1.SendMsg(msg=ai_response, who=list_name[0])
    except Exception as e:
        print(f"发送每日建议时发生错误: {str(e)}")


def read_weather_info(file_path):
    """读取天气信息并返回"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read().strip()
    except FileNotFoundError:
        print("天气信息文件未找到")
        return ""
    except Exception as e:
        print(f"读取天气信息时发生错误: {str(e)}")
        return ""


def handle_user_query(wx1, user_input):
    """处理用户的天气相关提问"""
    # 从文件中读取天气信息作为知识库
    weather_info = read_weather_info('weather.txt')

    # 使用 AI 获取用户查询的响应
    ai_response = get_qianwen_response(user_input, knowledge_base=weather_info)

    wx1.SendMsg(msg=ai_response, who=list_name[0])


def main(wx1, msg):
    if msg.startswith("AI"):
        user_input = msg[2:].strip()
        handle_user_query(wx1, user_input)



if __name__ == '__main__':
    wx = WeChat()  # 初始化微信机器人
    # 定时发送早安和晚安消息
    schedule.every().day.at("07:00").do(send_message, wx, "早安！☀️今天是元气满满的一天", list_name[0])
    schedule.every().day.at("22:00").do(send_message, wx, "晚安！🌙已入夜该睡觉了", list_name[0])

    while True:
        msgs = wx.GetAllMessage()  # 获取所有新消息
        current_time = datetime.now()
        if msgs:
            if msgs[-1].type == "friend":  # 仅处理来自好友的消息
                main(wx, msgs[-1].content)  # 处理消息
        schedule.run_pending()  # 检查并运行定时任务
        time.sleep(60)  # 等待60秒
        if current_time.hour == 16 and current_time.minute == 37:  # 调整为您需要的时间
            send_daily_advice(wx)
            time.sleep(60)  # 睡眠60秒，避免重复发送
        else:
            msgs = wx.GetAllMessage()
            if msgs:
                if msgs[-1].type == "friend":
                    main(wx, msgs[-1].content)

        time.sleep(1)  # 每秒检查一次用户询问